#!/bin/bash

# import configuration
. "`dirname $0`/ploff-config.sh"

# log levels
export LOG_ERROR="0"
export LOG_INFO="1"
export LOG_DEBUG="2"

export DIR_ROOT_INPUT=$1
export DIR_ROOT_OUTPUT=$2

export DIR_INPUT_BACKUP=$DIR_ROOT_INPUT/backup

# 0. check if script already running
export lf=/tmp/ploffPidLockFile
# create empty lock file if none exists
cat /dev/null >> $lf
read lastPID < $lf
# if lastPID is not null and a process with that pid exists , exit
if [ ! -z "$lastPID" -a -d /proc/$lastPID ]; then 
	[ $LOG_LEVEL -ge $LOG_ERROR ] && echo "ploff script is already running (process $lastPID)"
	exit;
fi
# save my pid in the lock file
echo $$ > $lf
# sleep just to make testing easier

# 1. check whether there are files to process
for PROFILE in ${PROFILES[*]}
do

export DIR_INPUT=$DIR_ROOT_INPUT/$PROFILE
export DIR_OUTPUT=$DIR_ROOT_OUTPUT/$PROFILE
if [ "$(ls -A $DIR_INPUT)" ]; then
     [ $LOG_LEVEL -ge $LOG_DEBUG ] && echo "There are new documents in inbox $DIR_INPUT."
     
     # select a (the first) file of inbox
     export FILE_INPUT=`ls -1 "$DIR_INPUT" | head -1`
     export FILE_INPUT_PATH=$DIR_INPUT/$FILE_INPUT
     [ $LOG_LEVEL -ge $LOG_DEBUG ] && echo "Start processing file $FILE_INPUT"
  
  # 2. copy file to inbox-backup
     mkdir -p $DIR_INPUT_BACKUP/$PROFILE
     
     cp $FILE_INPUT_PATH $DIR_INPUT_BACKUP/$PROFILE/
     [ $LOG_LEVEL -ge $LOG_DEBUG ] && echo "Created backup of original file into $DIR_INPUT_BACKUP"
     
  # 3. create temporary directory and copy file
     export DIR_TMP=/tmp/tmp$FILE_INPUT
     rm -r $DIR_TMP
     mkdir -p $DIR_TMP
     
     cp $FILE_INPUT_PATH $DIR_TMP/
     rm $FILE_INPUT_PATH
     [ $LOG_LEVEL -ge $LOG_DEBUG ] && echo "Removed file from inbox"
     
  # 4. OCR the temp file
    [ $LOG_LEVEL -ge $LOG_DEBUG ] && echo "Start OCR job"
    $CMD_OCRMYPDF -l deu $DIR_TMP/$FILE_INPUT $DIR_TMP/output.pdf
  # 5. rename result to PLOFF-<date>-<counter> and copy to final destination    
  	[ $LOG_LEVEL -ge $LOG_DEBUG ] && echo "Finished OCR job"
  
  # parse scan count number
  export SCAN_COUNT="${FILE_INPUT#*_}"
  export SCAN_COUNT="${SCAN_COUNT%%.*}" 
  export DATE=`date "+%Y-%m-%d"`
  
  export FILE_OUTPUT=PLOFF-$DATE-$SCAN_COUNT.pdf
  
  cp $DIR_TMP/output.pdf $DIR_OUTPUT/$FILE_OUTPUT
  [ $LOG_LEVEL -ge $LOG_DEBUG ] && echo "Wrote result to $DIR_OUTPUT/$FILE_OUTPUT"
  
  # 6. cleanup
  rm -r $DIR_TMP
  rm -r $DIR_OCRMYPDF/tmp/*
  [ $LOG_LEVEL -ge $LOG_DEBUG ] && echo "Cleaned up tmp files"
  rm $lf
  
else
    [ $LOG_LEVEL -ge $LOG_DEBUG ] && echo "Inbox $DIR_INPUT is empty. Nothing to do for profile $PROFILE."
fi
done
